import ResLoader from "../Libs/ResLoader";

export class Toast {

    public static instance: Toast;

    private toastNode: cc.Node;

    public static getInstance(): Toast {
        if (Toast.instance == null) {
            Toast.instance = new Toast();
        }
        return Toast.instance;
    }

    //创建节点
    private async createToastNode() {
        this.toastNode = new cc.Node("ToastNode")
        let sprite: cc.Sprite = this.toastNode.addComponent(cc.Sprite)

        let labelNode = new cc.Node("Message")
        labelNode.addComponent(cc.Label)

        this.toastNode.addChild(labelNode)

        await ResLoader.load("texture/toast-bg", cc.SpriteFrame).then((asset: cc.SpriteFrame) => {
            asset.addRef();
            sprite.spriteFrame = asset
        })
    }


    public async show(message: string) {
        if( !this.toastNode){
            await this.createToastNode()
        } 

        let node = cc.instantiate(this.toastNode)
        node.getChildByName("Message").getComponent(cc.Label).string = message

        cc.director.getScene().getChildByName("Canvas").addChild(node);

        cc.tween(node)
            .to(0.2, { position: cc.v3(0, 20, 0) })
            .delay(0.3)
            .to(0.3, { opacity: 0 })
            .call(() => {
                node.destroy()
            })
            .start();
    }
}

export default Toast.getInstance()